/* api */
import * as ProjectManageApi from '@src/api/ProjectManage';
import * as PassApi from '@src/api/PassApi';
/* entity */
import Field from '@model/entity/Field';
/* model */
import { systemFields, customStatusList, topSystemFields, bottomSystemFields } from '@src/modules/projectManage/taskManageList/model';
import MsgModel from '@model/MsgModel';
import Page from '@model/Page';
/* enum */
import TableNameEnum from '@model/enum/TableNameEnum';
/* util */
import { message } from '@src/util/message';
import Log from '@src/util/log';
/* hooks */
import { useLoading } from '@hooks/useLoading';
/* vue */
import { Ref, ref } from 'vue';

interface Input {
  number: number;
  taskStatus: string;
}

// 获取项目状态
function useFetchTaskManageStatusList() {
  const dataStatusList: any = ref([]);

  const fetchTaskManageStatusList = ({ searchType }) => {
    const params = {
      createViewType: 'ALL',
      searchType
    }

    const allKey = (key: string) => {
      return key === 'ALL' ? '' : key;
    }
    const convertObject = (info: Input) => {
      return {
        label: customStatusList[info.taskStatus],
        number: info.number || 0,
        value: allKey(info.taskStatus)
      };
    }

    return (
      ProjectManageApi.getTaskManageStateStatus(params).then((res: any) => {
        if (MsgModel.isSuccess(res)) {

          const data = res?.data || [];
          dataStatusList.value = data.map((info: Input) => convertObject(info));
          
          // 添加缺少的项
          for (const key in customStatusList) {
            if (!data.some((x: any) => x.taskStatus === key)) {
              dataStatusList.value.push({
                label: customStatusList[key],
                number: 0,
                value: allKey(key)
              });
            }
          }

        } else {
          message.error(res.message);
        }

        return dataStatusList.value;

      }).catch((error: any) => {
        Log.error(error, fetchTaskManageStatusList.name);
      })
    )
  }

  return {
    dataStatusList,
    fetchTaskManageStatusList,
  }
}

// 获取表格表头数据
function useFetchTaskManageFieldList() {
  // 字段列表
  const fields = ref([] as Field[]);

  const fetchTaskManageFieldList = (templateId: string, fromPage: string = 'list') => {
    return (
      ProjectManageApi.getProjectTypeField({ templateId, tableName: TableNameEnum.TaskManage }).then((res: any) => {
        if (MsgModel.isSuccess(res)) {
          // 合并固定系统字段
          let allFields = [];
          if(fromPage === 'list') {
            allFields = [...res?.data || [], ...systemFields];
          }else {
            allFields = [...topSystemFields, ...res?.data || [], ...bottomSystemFields];
          }


          fields.value = allFields.map((item: any) => {
            // 先把模板id去掉，不传到选择列组件里面，选择列组件对模板id做了处理
            const { templateId, ...other } = item;
            return other;
          });
        } else {
          message.error(res.message);
        }

        return fields.value;

      }).catch((error: any) => {
        Log.error(error, fetchTaskManageFieldList.name);
      })
    )
  }

  return {
    fields,
    fetchTaskManageFieldList,
  }
}

// 获取项目列表数据
function useFetchTaskManageTableList() {
  // 加载状态
  const { loading, showLoading, hideLoading } = useLoading();

  const dataList = ref([]);
  const dataListPageInfo: Ref<Page> = ref(new Page());

  const fetchTaskManageTableList = (searchParams: any) => {
    showLoading();

    return (
      ProjectManageApi.getTaskManageList(searchParams).then((res: any) => {
        if (MsgModel.isSuccess(res)) {
          dataListPageInfo.value = (res?.result || new Page()) as Page;
          dataList.value = (res?.result?.list || []);
        } else {
          message.error(res.message);
        }

        return dataList.value;

      }).catch((error: any) => {
        Log.error(error, fetchTaskManageTableList.name);
      }).finally(() => {
        hideLoading();
      })
    )
  }

  return {
    loading,
    dataList,
    dataListPageInfo,
    fetchTaskManageTableList,
  }
}

// 获取按钮权限
function useFetchTaskManageAuth() {
  // 加载状态
  const { loading, showLoading, hideLoading } = useLoading();

  const btnAuth = ref({
    deleteProjectAuth: false, // 删除
    editProjectAuth: false, // 编辑
    viewProjectDetailAuth: true, // 详情页面
  });

  const fetchProjectBtn = (params: any) => {
    showLoading();

    ProjectManageApi.projectTypeRoleBtn(params).then((res: any) => {
      if (!res.success) {
        return message.error(res.message);
      }

      btnAuth.value = res.data;
      return btnAuth.value;
    }).catch((error: any) => {
      Log.error(error, fetchProjectBtn.name);
    }).finally(() => {
      hideLoading();
    })
  };

  return {
    btnAuth,
    fetchProjectBtn
  }
}

export {
  useFetchTaskManageStatusList,
  useFetchTaskManageFieldList,
  useFetchTaskManageTableList,
  useFetchTaskManageAuth,
}
